
const Controller = require('egg').Controller

class DevicesController extends Controller {
  constructor(ctx) {
    super(ctx)

    this.createRule = {
      name: { type: 'string', required: true, allowEmpty: false },
      deviceid: { type: 'string', required: true, allowEmpty: false }
    }
  }

  // 获取所有角色(分页/模糊)
  async index() {
    const { ctx, service } = this
    const payload = ctx.query
    let _id = ctx.state.user && ctx.state.user.data._id // GET ID
    const rid = ctx.state.user && ctx.state.user.data.role // GET ID
    const role = await ctx.model.Role.findById(rid)

    if (role && role.access === 'admin') {
      _id = undefined
    }
    const res = await service.devices.index(payload, _id)
    ctx.helper.success({ ctx, res })
  }

  // 新增之前调用(默认值，不一定需要)
  async new() {
    const { ctx, service } = this
    const payload = ctx.query
    const res = await service.devices.new(payload)
    ctx.helper.success({ ctx, res })
  }

  // 获取单个角色
  async show() {
    const { ctx, service } = this
    const { id } = ctx.params
    const res = await service.devices.show(id)
    ctx.helper.success({ ctx, res })
  }

  // 编辑之前调用 根据具体业务修改代码 默认和show相同
  async edit() {
    await this.show()
  }

  // 创建角色
  async create() {
    const { ctx, service } = this
    ctx.validate(this.createRule)
    const payload = ctx.request.body || {}
    const _id = ctx.state.user && ctx.state.user.data._id // GET ID
    payload.user = _id
    const res = await service.devices.create(payload)
    ctx.helper.success({ ctx, res })
  }

  // 修改角色
  async update() {
    const { ctx, service } = this
    ctx.validate(this.createRule)
    const { id } = ctx.params
    const payload = ctx.request.body || {}
    if (!payload.user) {
      const _id = ctx.state.user && ctx.state.user.data._id // GET ID
      payload.user = _id
    }
    await service.devices.update(id, payload)
    ctx.helper.success({ ctx })
  }

  


  // 删除单个角色
  async destroy() {
    const { ctx, service } = this
    const { id } = ctx.params
    await service.devices.destroy(id)
    ctx.helper.success({ ctx })
  }

  // 获取所有角色(分页/模糊)
  async mine() {
    const { ctx, service } = this

    const _id = ctx.state.user.data._id
    const payload = ctx.query

    // 调用 Service 进行业务处理
    const res = await service.devices.index(payload, _id)
    ctx.helper.success({ ctx, res })
  }

  // 更新最近24小时的数据
  async getFlow() {
    const { ctx, service } = this
    const { id } = ctx.params
    const device = await ctx.model.Devices.findById(id)

    if (!device) {
      ctx.throw(404, 'devices not found')
    }

    // console.log(device)

    const count = await service.flows.getFlows(device, 0 , 24)
    ctx.helper.success({ ctx ,code : 0 ,msg: '更新' + count + '条数据'})
  }
}

module.exports = DevicesController

